document.addEventListener('DOMContentLoaded', function () {
    const BASE_URL = ''; // 您的后端服务地址

    // 初始化 ECharts 实例
    var pieChart = echarts.init(document.getElementById('pieChart'));
    var lineChart = echarts.init(document.getElementById('lineChart'));

    // 显示加载动画
    pieChart.showLoading();
    lineChart.showLoading();

    // 鉴权
    const token = localStorage.getItem('token');
    const headers = {
        'Content-Type': 'application/json'
    };
    if (token) {
        headers['Authorization'] = 'Bearer ' + token;
    }

    async function fetchData(url) {
        try {
            const response = await fetch(url, { headers });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
            }
            const result = await response.json();

            // 检查后端是否直接返回了数组
            if (Array.isArray(result)) {
                return result;
            }

            // 检查后端是否返回了 { code: 1, data: [...] } 格式
            if (result.code === 1 && Array.isArray(result.data)) {
                return result.data;
            }

            // 如果两种格式都不是，则数据无效
            console.warn('API Warning: Response for charts is not in a recognized format', result);
            return [];

        } catch (error) {
            console.error('Error fetching data for charts:', error);
            return [];
        }
    }

    async function getAndRenderCharts() {
        pieChart.showLoading();
        lineChart.showLoading();
        try {
            // 使用您截图中的、最终正确的接口地址
            const salesData = await fetchData(`${BASE_URL}/api/sale_getall`);

            // 调用函数更新顶部卡片和下方图表
            updateSummaryCards(salesData);

            if (!salesData || salesData.length === 0) {
                console.warn("No sales data received from the server.");
                pieChart.hideLoading();
                lineChart.hideLoading();
                // 可以在此处显示"暂无数据"的提示
                pieChart.setOption({ title: { text: '分类占比分析\n\n暂无数据', left: 'center', top: 'center' } });
                lineChart.setOption({ title: { text: '7天销售趋势分析\n\n暂无数据', left: 'center', top: 'center' } });
                return;
            }

            // --- 7天销售趋势分析 (Line Chart) ---
            // 智能寻找数据中的最新日期作为基准
            const latestDate = new Date(
                Math.max(
                    ...salesData
                        .filter(item => item.date && !isNaN(new Date(item.date)))
                        .map(item => new Date(item.date))
                )
            );

            const sevenDaysAgo = new Date(latestDate);
            sevenDaysAgo.setDate(latestDate.getDate() - 6); // 获取7天的时间范围

            const dailySales = {};
            const dateLabels = [];
            // 初始化最近7天的数据和标签
            for (let i = 6; i >= 0; i--) {
                const d = new Date(latestDate);
                d.setDate(d.getDate() - i);
                const dateStr = d.toISOString().split('T')[0];
                dateLabels.push(dateStr);
                dailySales[dateStr] = 0;
            }

            // 筛选并累加这7天内的数据
            salesData.forEach(item => {
                if (item.date) {
                    const saleDate = new Date(item.date);
                    if (saleDate >= sevenDaysAgo && saleDate <= latestDate) {
                        const dateStr = saleDate.toISOString().split('T')[0];
                        if (dailySales.hasOwnProperty(dateStr)) {
                            dailySales[dateStr] += (item.total_price ?? 0);
                        }
                    }
                }
            });

            // --- 分类占比分析 (Pie Chart) -> 改为 商品销售占比分析 ---
            const productSales = {};
            salesData.forEach(item => {
                if (!item) return; // 跳过空项目
                const productName = item.name || '未知商品';
                const price = item.total_price ?? 0;
                if (!productSales[productName]) {
                    productSales[productName] = 0;
                }
                productSales[productName] += price;
            });

            const pieData = Object.keys(productSales).map(name => {
                return { name, value: productSales[name] };
            });

            // 渲染折线图
            const lineOption = {
                xAxis: { type: 'category', data: dateLabels },
                yAxis: { type: 'value' },
                tooltip: { trigger: 'axis' },
                series: [{
                    name: '销售额',
                    data: dateLabels.map(label => dailySales[label]),
                    type: 'line',
                    smooth: true
                }]
            };
            lineChart.hideLoading();
            lineChart.setOption(lineOption);
            
            // 渲染饼图
            const pieOption = {
                title: {
                    text: '各商品销售额占比',
                    left: 'center'
                },
                tooltip: { trigger: 'item' },
                legend: {
                    type: 'scroll',
                    orient: 'horizontal',
                    bottom: 10,
                    left: 'center',
                    padding: [5, 5, 15, 5],
                    itemGap: 20
                },
                series: [{
                    name: '商品销售额',
                    type: 'pie',
                    radius: ['40%', '65%'],
                    center: ['50%', '50%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: { show: false },
                    emphasis: {
                        label: { show: true, fontSize: '20', fontWeight: 'bold' }
                    },
                    data: pieData
                }]
            };
            pieChart.hideLoading();
            pieChart.setOption(pieOption);
        } catch (error) {
            console.error('Error rendering charts:', error);
            pieChart.hideLoading();
            lineChart.hideLoading();
        }
    }

    getAndRenderCharts();

    function updateSummaryCards(salesData) {
        // 找到显示数据的元素
        const salesTodayEl = document.getElementById('sales-today');
        const ordersTodayEl = document.getElementById('orders-today');
        const itemsSoldEl = document.getElementById('items-sold-today');
        const memberOrdersEl = document.getElementById('member-orders-today');

        if (!salesTodayEl || !ordersTodayEl || !itemsSoldEl || !memberOrdersEl) {
            console.error('一个或多个汇总卡片元素未找到!');
            return;
        }

        // 获取今天的真实日期，格式为 YYYY-MM-DD
        const todayStr = new Date().toISOString().split('T')[0];

        // 筛选出与今天日期匹配的销售数据
        const todaySalesData = salesData.filter(item => 
            item.date && item.date.startsWith(todayStr)
        );

        // 1. 计算今日销售额
        const totalSales = todaySalesData.reduce((sum, item) => sum + (item.total_price ?? 0), 0);

        // 2. 计算今日订单数 (假设每条记录是一笔订单)
        const totalOrders = todaySalesData.length;

        // 3. 计算今日销售商品总数
        const totalItems = todaySalesData.reduce((sum, item) => sum + (item.amount ?? 0), 0);

        // 4. 会员订单数 (当前数据无法区分，暂定为 N/A)
        const memberOrders = 'N/A'; 

        // 更新页面上的显示
        salesTodayEl.textContent = totalSales.toFixed(2);
        ordersTodayEl.textContent = totalOrders;
        itemsSoldEl.textContent = totalItems;
        memberOrdersEl.textContent = memberOrders;
    }

}); 